import { createSlice } from "@reduxjs/toolkit";
import axios from "axios";

const counterStore = createSlice({
    name:'number',
    initialState:{ // 初始化state
        count:12,
        age:18
    },
    // 修改状态的方法  同步方法  支持直接修改
    reducers:{ // state的操作方法
        addCount(state){
            state.count++
        },
        deleteCount(state){
            state.count--
        },
        addNumber(state,action){
            console.log('action:',action)
            state.count = action.payload
        }
    }
})

// 解构出来 actionCreater 函数
const { addCount,deleteCount,addNumber} = counterStore.actions

/**
 * 编写异步
 * 编写异步请求
 * 触发同步 reducers
 * */
const getNumber = ()=>{
    return async (dispatch)=>{
        // 编写异步请求
        const res = await axios.get(' http://localhost:3000')
        // 触发同步 reducers
        dispatch(addNumber(res.data))
    }
}

export { getNumber }

// 获取 reducers
const reducers = counterStore.reducer

/**
 * 以按需导出的方式导出 actionCreater
 * 页面引入触发的同步方法，修改状态值
 * */
export { addCount, deleteCount, addNumber }

// 以默认方式导出 reducers
export default reducers
